<?php
class Controller_Sales_Edm extends Controller_Abstract
{
	function actionCreate()
	{
		$this->_view['title'] = '添加邮件';
		
		$currentAccount = empty ( $_GET["bmail_account"] ) ? "reg_edm" : $_GET["bmail_account"];
		$currentSite = empty ( $_GET["site_selector"] ) ? "iwowcase.com" : $_GET["site_selector"];
		Helper_BSS_API_BMAIL::initAccount($currentAccount);
		
		$this->_view['bmailAccount'] = Helper_BSS_API_BMAIL::$uaccountList;
		$this->_view['currentAccount'] = $currentAccount;
		$this->_view['currentSite'] = $currentSite;
		
		$currentFolderName = empty($_GET["folder_selector"]) ? "" : $_GET["folder_selector"];
		$currentYear = empty($_GET["year_selector"]) ? date("Y") : $_GET["year_selector"];
		
		$mailFolderName = Helper_BSS_API_BMAIL::getSourceMailFolderNameList($currentYear,$currentSite);
		$this->_view['mailfoldername'] = $mailFolderName;

		$this->_view['currentFolderName'] = $currentFolderName;
		$this->_view['currentYear'] = $currentYear;
		
		/**
		 * 年份选择器
		 */
		$nowYear = date("Y");
		$yearSelector = array();
		
		for ( $i = 0 ; $i < 5 ; $i++ ) {
			$yearSelector[] = $nowYear - $i;
		}
		
		$this->_view['yearSelector'] = $yearSelector;
		
		/**
		 * 客户邮件列表 选择器
		 */
		$toMailGroup = Helper_BSS_API_BMAIL::getMailGroupList();
		$this->_view['toMailGroup'] = $toMailGroup;
		
		
		if (!empty($currentFolderName)) {
			$currentMailContents = Helper_BSS_API_BMAIL::getSourceMailContent($currentFolderName, $currentYear, $currentSite);
			$this->_view['name'] = $currentMailContents['name'];
			$this->_view['subjects'] = $currentMailContents['subjects'];
			$this->_view['html_contents'] = $currentMailContents['html_contents'];
			$this->_view['schedule_date'] = $currentMailContents['schedule_date'];
			$this->_view['from_mail'] = '';
			$this->_view['from_name'] = '';
			$this->_view['reply_email'] = '';
		} else {
			$this->_view['name'] = '';
			$this->_view['subjects'] = '';
			$this->_view['schedule_date'] = '';
			$this->_view['html_contents'] = '';
			$this->_view['from_mail'] = '';
			$this->_view['from_name'] = '';
			$this->_view['reply_email'] = '';
		}
			
	}
	
	function actionCreateSave()
	{
		$this->_view['title'] = '添加邮件保存';
		$currentAccount = empty ( $_POST["bmail_account"] ) ? "reg_edm" : $_POST["bmail_account"];
		Helper_BSS_API_BMAIL::initAccount($currentAccount);
		
		$name = $_POST["name"]; 
		$subjects = $_POST["subjects"];
		$scheduleDate = $_POST["schedule_date"];
		$to_listid = $_POST["to_listid"];
		$from_mail = $_POST["from_mail"];
		$from_name = $_POST["from_name"];
		$reply_email = $_POST["reply_email"];
		$html_contents = $_POST["html_contents"];
		
		$result = Helper_BSS_API_BMAIL::createEDM($name, $subjects, $scheduleDate, $to_listid, $from_mail, $from_name, $reply_email, $html_contents);
		
		if ($result) {
			
			return $this->_redirectMessage('Email add Successful!', 'Test mail has been sent to '.$reply_email.', please check it out.', url('Sales::Edm/Create'), SUCCESS);
			
		} else {
			
			return $this->_redirectMessage('Email add Failure!', 'Please Check you input.', url('Sales::Edm/Create'), FAILURE);
			
		}

	}
	
	function actionMailGroupList()
	{
		$this->_view['title'] = '客户邮箱组管理';
		
		$currentAccount = empty ( $_GET["bmail_account"] ) ? "reg_edm" : $_GET["bmail_account"];
		Helper_BSS_API_BMAIL::initAccount($currentAccount);
		
		$this->_view['bmailAccount'] = Helper_BSS_API_BMAIL::$uaccountList;
		$this->_view['currentAccount'] = $currentAccount;
		
		$mailgrounp = Helper_BSS_API_BMAIL::getMailGroupList();
		$this->_view['mailgrounp'] = $mailgrounp;
		
		$subAcitonDisplay = '';
		$actionListID = '';
		
		if ( !empty($_GET["sub_action"]) and !empty($_GET["lid"]) ) {
			
			switch ($_GET["sub_action"]) {
				case "add":
					$subAcitonDisplay = "add";
					$actionListID = $_GET["lid"];
					break;
					
				case "del":
					$subAcitonDisplay = "del";
					$actionListID = $_GET["lid"];
					break;
			}
			
		}
		
		$this->_view['subAcitonDisplay'] = $subAcitonDisplay;
		$this->_view['actionListID'] = $actionListID;
		
	}
	
	function actionMailGroupAdd()
	{
		$this->_view['title'] = '添加客户';
		$currentAccount = empty ( $_POST["bmail_account"] ) ? "reg_edm" : $_POST["bmail_account"];
		Helper_BSS_API_BMAIL::initAccount($currentAccount);
		
		$listID = $_POST["list_id"]; 
		$emails = $_POST["emails"];
		
		$explodeEmailArray = explode(",", $emails);
		
		foreach ($explodeEmailArray as $v) {
			$customerInfo[]  = array("email" => $v);
		}
		
		$result = Helper_BSS_API_BMAIL::addMailToMailGroup($listID, $customerInfo);
		
		if ($result) {
			return $this->_redirectMessage('Email add Successful!', $result . " records added", url('Sales::Edm/MailGroupList')."&bmail_account={$currentAccount}", SUCCESS);
		} else {
			return $this->_redirectMessage('Email add Failure!', 'Please Check you input.', url('Sales::Edm/MailGroupList')."&bmail_account={$currentAccount}", FAILURE);
		}
		
	}
	
	function actionMailGroupDel()
	{
		$this->_view['title'] = '删除客户';
		$currentAccount = empty ( $_POST["bmail_account"] ) ? "reg_edm" : $_POST["bmail_account"];
		Helper_BSS_API_BMAIL::initAccount($currentAccount);
		
		$listID = $_POST["list_id"]; 
		$emails = $_POST["emails"];
		
		$explodeEmailArray = explode(",", $emails);
		
		$result = 0;
		
		foreach ($explodeEmailArray as $v) {
			$result += Helper_BSS_API_BMAIL::delMailFromMailGroup($listID, $v);
		}
		
		if ($result > 0) {
			return $this->_redirectMessage('Email del Successful!', $result . " records deled", url('Sales::Edm/MailGroupList')."&bmail_account={$currentAccount}", SUCCESS);
		} else {
			return $this->_redirectMessage('Email del Failure!', 'Please Check you input.', url('Sales::Edm/MailGroupList')."&bmail_account={$currentAccount}", FAILURE);
		}
		
	}
	
	function actionEdmReport()
	{
		$this->_view['title'] = '邮件报表';
		$currentAccount = empty ( $_GET["bmail_account"] ) ? "reg_edm" : $_GET["bmail_account"];
		Helper_BSS_API_BMAIL::initAccount($currentAccount);
		
		$this->_view['bmailAccount'] = Helper_BSS_API_BMAIL::$uaccountList;
		$this->_view['currentAccount'] = $currentAccount;
		
		$emaillists = Helper_BSS_API_BMAIL::getEDMList();
		$this->_view['emaillists'] = $emaillists;
	}
	
	function actionSiteRegCustomerReport() {
		
		$this->_view['title'] = '站点客户注册报表';
		
		$bdate = empty($_GET["bdate"]) ? date("Y-m-d", time()-3600*24*8) : $_GET["bdate"];
		$edate = empty($_GET["edate"]) ? date("Y-m-d") : $_GET["edate"];		
		
		$this->_view['bdate'] = $bdate;
		$this->_view['edate'] = $edate;
		
		$shopID = empty($_GET["shop_id"]) ? 53 : $_GET["shop_id"];
		
		$dailyReg = array();
		
		for ($i = strtotime($edate) ; $i >= strtotime($bdate) ; $i -= 86400 ) {
			
			$thisBeginDate = date("Y-m-d", $i);
			$thisEndDate = date("Y-m-d", $i + 86400);
			
			$dReg = QDB::getConn()->execute("select count(customer_reg_info.id) count from customer_reg_info where reg_time >= '{$thisBeginDate}' and reg_time <= '{$thisEndDate}' and shop_id = '{$shopID}'")->fetchOne();
			$ebayReg = QDB::getConn()->execute("select count(customer_reg_info.id) count from customer_reg_info, sales_order_customer_categories where reg_time >= '{$thisBeginDate}' and reg_time <= '{$thisEndDate}' and customer_reg_info.shop_id = '{$shopID}' and customer_reg_info.email = sales_order_customer_categories.email")->fetchOne();
			
			$dailyReg[] = array(
			
				"date" => date("Y-m-d",$i),
				"week" => date("D",$i),
				"reg_total" => $dReg,
				"reg_from_ebay" => $ebayReg
			);
			
		}
		
		$this->_view['dailyreg'] = $dailyReg;
		
		
	}
	
	function actionGetCustomerEmail() {
		
		$this->_view['title'] = '获取客户邮箱';
		$currentAccount = empty ( $_GET["bmail_account"] ) ? "reg_edm" : $_GET["bmail_account"];
		$currentMailServer = empty ( $_GET["mail_server"] ) ? array("GoogleMail","AolMail","Other",) : $_GET["mail_server"];
		Helper_BSS_API_BMAIL::initAccount($currentAccount);
		
		$this->_view['bmailAccount'] = Helper_BSS_API_BMAIL::$uaccountList;
		$this->_view['currentAccount'] = $currentAccount;
		$this->_view['currentMailServer'] = $currentMailServer;
		
		$toMailGroup = Helper_BSS_API_BMAIL::getMailGroupList();
		$this->_view['toMailGroup'] = $toMailGroup;
		
		$listMapping = array();
		
		foreach ($toMailGroup as $v) {
			$listMapping[$v["id"]] = $v["listname"];
		}
		
		$categories = Product_Categories::find('parent_id=?', "0")->asArray()->getAll();
		$this->_view['categories'] = $categories;
		
		$searchType = empty($_GET["search_type"]) ? "zen_cart_sites" : $_GET["search_type"];
		$this->_view['currentSearchType'] = $searchType;
		
		$toListID = empty($_GET["to_listid"]) ? "" : $_GET["to_listid"];
		$this->_view['toListID'] = $toListID;
		
		$needSync = empty($_GET["need_sync"]) ? "" : $_GET["need_sync"];
		$this->_view['needSync'] = $needSync;
		
		$bdate = empty($_GET["bdate"]) ? date("Y-m-d", time()-3600*24*8) : $_GET["bdate"];
		$edate = empty($_GET["edate"]) ? date("Y-m-d") : $_GET["edate"];		
		
		$this->_view['bdate'] = $bdate;
		$this->_view['edate'] = $edate;

		switch ($searchType) {
			
			case "zen_cart_sites":
				
				$shopID = empty($_GET["shop_id"]) ? 53 : $_GET["shop_id"];
				$this->_view['currentCatID'] = 0;
				
				$regSource = empty($_GET["reg_source"]) ? "all" : $_GET["reg_source"];
				$this->_view['currentRegSource'] = $regSource;
				
				$customerMailList = QDB::getConn()->execute("select * from customer_reg_info where reg_time >= '{$bdate}' and reg_time <= '{$edate} 23:59:59' and shop_id = '{$shopID}' order by reg_time desc")->fetchAll();
				
				$needSyncArray = array();
				
				foreach ($customerMailList as $k => $v) {
					
					if (!isset($listMapping[$v["sync_list_id"]])) $listMapping[$v["sync_list_id"]] = $v["sync_list_id"];
					
					$customerMailList[$k]["sync_status"] = $v["has_sync"] == 1 ? "<span title='List {$listMapping[$v["sync_list_id"]]} 最后一次同步时间 {$v["last_sync_time"]}' >同步</span>" : "-"; 
					
					$isEbayCustomer = QDB::getConn()->execute("select * from sales_order_customer_categories where email = '{$v["email"]}'")->fetchOne();
					
					$customerMailList[$k]["reg_source"] = !empty($isEbayCustomer) ? "ebay" : 'site';
					
					
					
					/* 暂且注释掉 eBay 相关信息，提升速度
					if (!empty($isEbayCustomer)) {	
						
						$eBayOrderStatus = QDB::getConn()->execute("SELECT sum( so.amount ) amount, count( so.id ) count FROM sales_order AS so, sales_order_customer_info AS soci WHERE so.id = soci.sales_order_id AND soci.email = '{$v["email"]}' AND so.shop_id != '{$shopID}'")->fetchRow();
						
						$customerMailList[$k]["ebay_order_count"] = $eBayOrderStatus["count"];
						$customerMailList[$k]["ebay_order_amount"] = round($eBayOrderStatus["amount"],2);
						$customerMailList[$k]["ebay_first_order_time"] = QDB::getConn()->execute("select so.sales_time time from sales_order as so, sales_order_customer_info as soci where so.id = soci.sales_order_id and soci.email = '{$v["email"]}' and so.shop_id != '{$shopID}' order by so.sales_time asc limit 1 ")->fetchOne();
												
					} else {	
						$customerMailList[$k]["ebay_order_count"] = "-";
						$customerMailList[$k]["ebay_order_amount"] = "-";
						$customerMailList[$k]["ebay_first_order_time"] = "-";
					}
					*/
					$siteOrderStatus = QDB::getConn()->execute("select sum(so.amount) amount, count(so.id) count from sales_order as so, sales_order_customer_info as soci where so.id = soci.sales_order_id and soci.email = '{$v["email"]}' and so.shop_id = '{$shopID}' ")->fetchRow();
					
					$customerMailList[$k]["site_order_count"] = $siteOrderStatus["count"];
					$customerMailList[$k]["site_order_amount"] = round($siteOrderStatus["amount"],2);
					$customerMailList[$k]["site_reg_time"] = $v["reg_time"];
					$customerMailList[$k]["site_last_login_time"] = $v["last_login_time"];
					
					if ($needSync == 1 and empty($v["has_sync"]) ) {
	
						$needSyncArray[] = array(
							'cid' => $v["id"],
							'email' => $v["email"],
							'firstname' => $v["first_name"],
							'lastname' => $v["last_name"],
						);
					}
					
				}
				
				for ($i = 0 ; $i < ceil(count($needSyncArray)/10); $i++ ) {
					
					$thisQ = array_slice($needSyncArray,$i*10,10);
					
					Helper_BSS_API_BMAIL::addMailToMailGroup( $toListID, $thisQ );
					
					foreach ($thisQ as $v) {					
						QDB::getConn()->execute("update customer_reg_info set has_sync = '1', sync_list_id = '{$toListID}', last_sync_time = '". date('Y-m-d H:i:s')."' where id = '{$v["cid"]}'");
					}
				}
				
				break;
				
			case "ebay_stores":
				$catID = $_GET["cat_id"];
				$this->_view['currentCatID'] = $catID;
				
				$mailServerFliterSql = " and email_server in ('" . implode("','",$currentMailServer) . "') ";
				
				
				$customerMailList = QDB::getConn()->execute("select * from sales_order_customer_categories 
															 where order_time >= '{$bdate}'
															 and order_time <= '{$edate} 23:59:59'
															 ". (empty($catID) ? '' : "and category_id = '{$catID}'") ."
															 ".$mailServerFliterSql."
															 order by order_time desc ")->fetchAll();
				
				$needSyncArray = array();
				
				foreach ($customerMailList as $k => $v) {
					
					$customerInfo = Sales_Order_Customer_Info::find("id = ?",$v["customer_id"])->order("id desc")->limit("1")->getOne();
					$firstCustomerInfo = Sales_Order_Customer_Info::find("id = ?",$v["customer_id"])->order("id asc")->limit("1")->getOne();
					
					$lastOrderInfo = Sales_Order::find("id = ?", $customerInfo["sales_order_id"])->getOne();
					$firstOrderInfo = Sales_Order::find("id = ?", $firstCustomerInfo["sales_order_id"])->getOne();
					$lastOrderShopInfo = Shop::find("id = ? ",$lastOrderInfo["shop_id"])->getOne();
					$categoryInfo = Product_Categories::find("id = ?",$v["category_id"])->getOne();
					
					$customerMailList[$k]["customer_ebay_id"] = $customerInfo["shop_buyer_id"];
					$customerMailList[$k]["shop_ebay_id"] = $lastOrderShopInfo["name"];
					$customerMailList[$k]["last_order_time"] = substr($lastOrderInfo["sales_time"],0,10); 
					$customerMailList[$k]["order_time"] = substr($firstOrderInfo["sales_time"],0.,10); 
					$customerMailList[$k]["category_name"] = $categoryInfo["name"]; 
					
					if (!isset($listMapping[$v["sync_list_id"]])) $listMapping[$v["sync_list_id"]] = $v["sync_list_id"];
					
					$customerMailList[$k]["sync_status"] = $v["has_sync"] == 1 ? "<span title='List {$listMapping[$v["sync_list_id"]]} 最后一次同步时间 {$v["last_sync_time"]}' >同步</span>" : "-"; 
					
					if ( $needSync == 1 and empty($v["has_sync"]) ) {
						
						$needSyncArray[] = array(
							'customer_id' => $v["customer_id"],
							'email' => $v["email"],
							'firstname' => $v["fullname"],
							'Date 1' => substr($firstOrderInfo["sales_time"],0,10),
							'Date 2' => substr($lastOrderInfo["sales_time"],0.,10),
							'Extra 3' => $lastOrderShopInfo["name"],
							'Extra 4' => $customerInfo["shop_buyer_id"],
						);
						
					}
					
				}
				
				for ($i = 0 ; $i < ceil(count($needSyncArray)/30); $i++ ) {
					
					$thisQ = array_slice($needSyncArray,$i*30,30);
					
					Helper_BSS_API_BMAIL::addMailToMailGroup( $toListID, $thisQ );
					
					foreach ($thisQ as $v) {					
						QDB::getConn()->execute("update sales_order_customer_categories set has_sync = '1', sync_list_id = '{$toListID}', last_sync_time = '". date('Y-m-d H:i:s')."' where customer_id = '{$v["customer_id"]}'");
					}
				}
				
				break;
			
			default:
				break;
		}
		
		$this->_view['customerMailList'] = $customerMailList;
		$this->_view['mailServer'] = array(
			"YahooMail",
			"MsMail",
			"GoogleMail",
			"AolMail",
			"Other",
		);
		
	}
	
}